<template>
  <q-page class="q-pa-md">
    <div class="q-mb-md">
      <q-btn @click="addRow" label="Add Row" color="primary" />
      <q-btn @click="saveChanges" label="Save Changes" color="positive" class="q-ml-sm" />
    </div>
    <q-table
      title="Editable Table"
      :rows-per-page-options="[20, 50, 100]"
      :data="tableData"
      :columns="columns"
      row-key="id"
    >
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td key="id" :props="props">
            {{ props.row.id }}
          </q-td>
          <q-td v-for="col in dynamicColumns" :key="col.name" :props="props">
            <q-input v-model="props.row[col.name]" dense debounce="300" @blur="props.row.__edited = true" />
          </q-td>
          <q-td key="actions" :props="props">
            <q-btn icon="delete" flat @click="deleteRow(props.row.id)" />
          </q-td>
        </q-tr>
      </template>
    </q-table>
  </q-page>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      columns: [
        { name: 'id', required: true, label: 'ID', field: 'id', align: 'left', sortable: true },

      ],
      dynamicColumns: [],
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.$axios.get('http://localhost:4444/data')
        .then(response => {
          this.tableData = response.data;
          if (this.tableData.length > 0) {
            this.dynamicColumns = Object.keys(this.tableData[0]).filter(key => key !== 'id').map(key => {
              return { name: key, align: 'left', label: key, field: key, sortable: true };
            });
            this.columns = [
              ...this.columns,
              ...this.dynamicColumns
            ];

            this.columns.push( { name: 'actions', label: 'Actions', field: 'actions', align: 'center' },)



          }
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
    },
    addRow() {
      const newId = this.tableData.length ? Math.max(...this.tableData.map(row => row.id)) + 1 : 1;
      const newRow = { id: newId };
      this.dynamicColumns.forEach(col => {
        newRow[col.name] = '';
      });
      this.tableData.push(newRow);
    },
    deleteRow(id) {
      this.tableData = this.tableData.filter(row => row.id !== id);
    },
    saveChanges() {
      const editedRows = this.tableData.filter(row => row.__edited);
      editedRows.forEach(row => {
        this.$axios.put(`http://localhost:4444/data/${row.id}`, row)
          .then(response => {
            console.log('Row updated:', response.data);
          })
          .catch(error => {
            console.error('Error updating row:', error);
          });
      });
      this.$axios.post('http://localhost:4444/data', this.tableData.filter(row => !row.__edited && !this.tableData.find(e => e.id === row.id)))
        .then(response => {
          console.log('Rows added:', response.data);
        })
        .catch(error => {
          console.error('Error adding rows:', error);
        });
      this.tableData.forEach(row => delete row.__edited);
      this.$q.notify({type: 'positive', message: 'Changes saved!'});
    },
  },
};
</script>

<style scoped>
.q-pa-md {
  padding: 16px;
}

.q-mb-md {
  margin-bottom: 16px;
}

.q-ml-sm {
  margin-left: 8px;
}
</style>
